/*
	Copyright (c) 2006-2008, Grant Jones <grant@gxjones.com>.
	All rights reserved.

	Redistribution and use in source and binary forms, with or
	without modification, are permitted provided that the following
	conditions are met:

		Redistributions of source code must retain the above copyright
		notice, this list of conditions and the following disclaimer.
		
		Redistributions in binary form must reproduce the above copyright
		notice, this list of conditions and the following disclaimer in
		the documentation and/or other materials provided with the
		distribution.
		
		Neither the name of the gxjones.com nor the names of its
		contributors may be used to endorse or promote products derived
		from this software without specific prior written permission.
	
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
	LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
	FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
	INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
	STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
	OF THE POSSIBILITY OF SUCH DAMAGE.
	
	http://www.opensource.org/licenses/bsd-license.php
*/

//
//  BaseGLView.m
//  Mote-M BaseCode
//
//  Created by Grant Jones on 7/24/08.
//

#import "BaseGLView.h"


@implementation BaseGLView

@synthesize dataSource, delegate;
@synthesize backingWidth, backingHeight;

- (id) init
{
	self = [super init];
	if (self != nil) {
		cmap_init(&_tc_schedule);	// must happen before any tc's are scheduled!
		
		_visibility = [self scheduledToggleController];
		_fade_speed = 1000.0f;
		_subviews = [[NSMutableArray alloc] init];
				
				
		_near_dist = 1.0f;
		_far_dist = 14.0f;
	}
	return self;
}

- (void) dealloc
{
	// cleanup all tcs:
	cmapEnumStruct e;
	int k;
	ToggleController *tc;

	for( cmap_enum(&_tc_schedule, &e); (tc = cmap_enum_next(&e, &k)); )
		[tc release];
	_tc_schedule.num = 0;
	if( _tc_schedule.kd ) 
		free( _tc_schedule.kd );
	
	[super dealloc];
}

#pragma mark Subview maangement

- (void)pushNewView:(BaseGLView *)glView withDelegate:(id)subview_delegate forDataSource:(id)subview_datasource {
	
	glView.delegate = subview_delegate;
	glView.dataSource = subview_datasource;
	glView.backingWidth = backingWidth;
	glView.backingHeight = backingHeight;	
	[glView loadTextures];	
	[_subviews addObject:glView];
}
- (void)popView {
	[_subviews removeLastObject];
}

#pragma mark Texture Handling Convenience management

- (void) purgeTextureCaches {
	/* subclasses should respond to this message by clearing any extra textures caches,
	** this is called during a low memory warning */
	int i;
	cmapEnumStruct e;
	int k;
	Texture2D *t;
	
	for( cmap_enum(&_texture_cache, &e); (t = cmap_enum_next(&e, &k)); ) { [t release]; }
#if TARGET_IPHONE_SIMULATOR
	NSLog(@"purged %d towerTreeView textures", _texture_cache.num );
#endif
	_texture_cache.num = 0;
	
	// also purge subviews:
	for( i = 0; i < [_subviews count]; i ++ )
		[[_subviews objectAtIndex:i] purgeTextureCaches];		
}
- (NSString *) filenameForGraphic:(int)graphic_name {
	/* subclasses should respond to this message with a filename to load for the specified graphic name */
	return nil;
}
- (Texture2D *) textureForGraphic:(int)graphic_name {
	Texture2D *t;
	t = cmap_lookup(&_texture_cache, graphic_name);
	if(t)
		return t;
	NSString *filename = [self filenameForGraphic:graphic_name];
	if(!filename)
		return nil;

	t = [[Texture2D alloc] initWithImage: [UIImage imageNamed:filename]];	
	glBindTexture(GL_TEXTURE_2D, [t name]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);	
	cmap_assign(&_texture_cache, graphic_name, t);
	
	return t;		
}
- (void) loadTextures {

}

#pragma mark Time Step handling

- (void)tickWithDelta:(double)delta_t {
	cmapEnumStruct e;
	int i;
	ToggleController *tc;

	for( cmap_enum(&_tc_schedule, &e); (tc = cmap_enum_next(&e, &i)); )
		[tc tickWithDelta:delta_t];

	for( i = 0; i < [_subviews count]; i ++ )
		[[_subviews objectAtIndex:i] tickWithDelta:delta_t];
}

#pragma mark Drawing

- (BOOL)isVisible {
	return ( [_visibility currentState] || [_visibility inTransition] );
}


- (void)draw {

}

- (void)drawView { 
	int i;
	if( ![self isVisible] )
		return;
		
	[self draw];

	// subviews are drawn ontop of current view:
	for( i = 0; i < [_subviews count]; i ++ )
		[[_subviews objectAtIndex:i] drawView];
}


// Replaces gluPerspective. Sets the frustum to perspective mode.
// fovY		- Field of vision in degrees in the y direction
// aspect	- Aspect ratio of the viewport
// zNear	- The near clipping distance
// zFar		- The far clipping distance

void perspectiveGL( GLfloat fovY, GLfloat aspect, GLfloat zNear, GLfloat zFar )
{
	const GLfloat pi = M_PI;
	GLfloat fW, fH;
//	fH = tan( (fovY / 2) / 180 * pi ) * zNear;
	fH = tan( fovY / 360 * pi ) * zNear;
	fW = fH * aspect;

	glFrustumf( -fW, fW, -fH, fH, zNear, zFar );
}

- (void)setPerspective {
	GLfloat aspect_ratio = (float)backingWidth/backingHeight;
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	perspectiveGL(45.0f, aspect_ratio, _near_dist, _far_dist);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

- (void)setOrtho {
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrthof(0.0f, backingWidth, 0, backingHeight, 0.0f, 1.0f);	
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

#pragma mark Touch Management

- (BOOL) shouldHandleTouchEvent { return /*[_visibility currentState]*/[self isVisible]; }

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	int i;
	i = [_subviews count];
	while(i)
	{
		i --;
		BaseGLView *view = [_subviews objectAtIndex:i];
		if( [view shouldHandleTouchEvent] ) {
			[view touchesBegan:touches withEvent:event];
			break;
		}
	}
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
	int i;	
	i = [_subviews count];
	while(i)
	{
		i --;
		BaseGLView *view = [_subviews objectAtIndex:i];
		if( [view shouldHandleTouchEvent] ) {
			[view touchesEnded:touches withEvent:event];
			return;
		}
	}
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	int i;	
	i = [_subviews count];
	while(i)
	{
		i --;
		BaseGLView *view = [_subviews objectAtIndex:i];
		if( [view shouldHandleTouchEvent] ) {
			[view touchesMoved:touches withEvent:event];
			return;
		}
	}
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {

}

#pragma mark Visibility Management

- (void) show {
	if( [_visibility currentState] && ![_visibility inTransition])
		return;	// already visible
	[_visibility setState:FALSE from:0.0f to:1.0f withSpeed:_fade_speed];
	[_visibility armTrigger:self selector:@selector(showFinished:)];
}
- (void) hide {
	if( ![_visibility currentState]  && ![_visibility inTransition])
		return;	// already hidden
	[_visibility setState:TRUE from:1.0f to:0.0f withSpeed:_fade_speed];
	[_visibility armTrigger:self selector:@selector(hideFinished:)];
}

- (void)hideFinished:(ToggleController *)tc {
	[_visibility setState:FALSE from:0.0f to:0.0f withSpeed:0.0f];	
}

- (void)showFinished:(ToggleController *)tc {
	[_visibility setState:TRUE from:1.0f to:1.0f withSpeed:0.0f];
}

#pragma mark Toggle Controller Scheduling and Management

- (ToggleController *)scheduledToggleController {
	ToggleController *tc = [[ToggleController alloc] init];
	int tc_uid = cmap_gethighestkey(&_tc_schedule)+1;
	[tc setUID:tc_uid];
	cmap_assign(&_tc_schedule, tc_uid, tc);

	// this class owns the toggle controller and must be released by removeToggleController
	return tc;
}
- (void)removeToggleController:(ToggleController *)tc {
	ToggleController *tc_check = cmap_remove(&_tc_schedule, [tc UID]);
	assert( tc_check == tc );

	[tc release];
}

@end
